package com.tz.cartelo.activity;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tz.cartelo.BaseApplication;
import com.tz.cartelo.R;
import com.tz.cartelo.constant.Api;
import com.tz.cartelo.constant.Key;
import com.tz.cartelo.model.DataParams;
import com.tz.cartelo.model.GoodsSubclass;
import com.tz.cartelo.result.ResultEditOrder;
import com.tz.cartelo.util.AES;
import com.tz.common.util.LogUtil;
import com.tz.common.util.NumberFormatUtil;
import com.tz.common.util.PreferencesUtils;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

/**
 * Created by Administrator on 2017/4/16.
 */

public class EditOrderActivity extends DataLoadActivity implements View.OnClickListener {
    private static final String TAG = "EditOrderActivity";
    private Api mApi;
    private List<EditText> mEditTextList;
    private List<GoodsSubclass> mGoodsSubclassList;
    private TextView editOrderTotalCountText;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_edit_order;
    }

    @Override
    protected void init() {
        findViewById(R.id.goods_details_center_layout).setOnClickListener(this);
        TextView edit_order = (TextView) findViewById(R.id.edit_order);
        TextView edit_order_submit = (TextView) findViewById(R.id.edit_order_submit);

        LinearLayout editOrderTotalCountLayout = (LinearLayout) findViewById(R.id.edit_order_total_count_layout);
        editOrderTotalCountText = (TextView) findViewById(R.id.edit_order_total_count_text);
        editOrderTotalCountText.setText("下单总数：" + 0);

        if (getIntent().getFlags() == Key.CLASSIFY_STOCK) {
            edit_order.setText("库存");
            edit_order_submit.setText("确定修改");
            editOrderTotalCountLayout.setVisibility(View.GONE);
        } else {
            editOrderTotalCountLayout.setVisibility(View.VISIBLE);
        }

        LinearLayout editOrderGoodsStyleLayout = (LinearLayout) findViewById(R.id.edit_order_goods_style_layout);
        findViewById(R.id.edit_order_submit_layout).setOnClickListener(this);
        mGoodsSubclassList = (List<GoodsSubclass>) getIntent().getSerializableExtra(Key.GOODS_STYLE);

        mEditTextList = new ArrayList<>();
        int groupType = 1;
        for (GoodsSubclass goodsSubclass : mGoodsSubclassList) {
            View goodsStyleView = LayoutInflater.from(this).inflate(R.layout.item_edit_order, null);
            View edit_order_line1 = goodsStyleView.findViewById(R.id.edit_order_line1);
            View edit_order_line2 = goodsStyleView.findViewById(R.id.edit_order_line2);
            View edit_order_gray_line1 = goodsStyleView.findViewById(R.id.edit_order_gray_line1);
            View edit_order_gray_line2 = goodsStyleView.findViewById(R.id.edit_order_gray_line2);
            LinearLayout editOrderLayout = (LinearLayout) goodsStyleView.findViewById(R.id.edit_order_layout);
            TextView editOrderText = (TextView) goodsStyleView.findViewById(R.id.edit_order_text);
            TextView editOrderReduceText = (TextView) goodsStyleView.findViewById(R.id.edit_order_reduce);
            TextView editStockReduceText = (TextView) goodsStyleView.findViewById(R.id.edit_stock_reduce);
            TextView editOrderAddText = (TextView) goodsStyleView.findViewById(R.id.edit_order_add);
            final EditText editOrderEdit = (EditText) goodsStyleView.findViewById(R.id.edit_order_edit);

            if (goodsSubclass.getTotalNum().equals("0")) {
                editOrderText.setTextColor(getResources().getColor(R.color.gray));
                editOrderReduceText.setTextColor(getResources().getColor(R.color.gray));
                editStockReduceText.setTextColor(getResources().getColor(R.color.gray));
                editOrderAddText.setTextColor(getResources().getColor(R.color.gray));
                editOrderEdit.setTextColor(getResources().getColor(R.color.gray));
                editOrderLayout.setBackgroundResource(R.drawable.shape_stroke_dash_frame);
                edit_order_line1.setVisibility(View.VISIBLE);
                edit_order_line2.setVisibility(View.VISIBLE);
                edit_order_gray_line1.setVisibility(View.GONE);
                edit_order_gray_line2.setVisibility(View.GONE);
            }

            editOrderText.setText(goodsSubclass.getAppearance());

            final int[] totalNum = {NumberFormatUtil.parseInt(goodsSubclass.getTotalNum())};
            final int[] startNum = {0};
            editOrderEdit.setText("0");

            if (getIntent().getFlags() == Key.CLASSIFY_STOCK) {
                editOrderAddText.setVisibility(View.GONE);
                editOrderReduceText.setVisibility(View.GONE);
                editStockReduceText.setVisibility(View.VISIBLE);
                editOrderEdit.setText(totalNum[0] + "");
                edit_order_line1.setVisibility(View.GONE);
            }


            if (groupType != Integer.parseInt(goodsSubclass.getGroupType())) {
                View grayLineView = LayoutInflater.from(this).inflate(R.layout.item_gray_line, null);
                editOrderGoodsStyleLayout.addView(grayLineView);
                groupType++;
            }
            editOrderGoodsStyleLayout.addView(goodsStyleView);

            editOrderReduceText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (startNum[0] > 0) {
                        startNum[0]--;
                        editOrderEdit.setText(startNum[0] + "");
                    }
                    setTotalCount();
                }
            });
            editStockReduceText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (totalNum[0] > 0) {
                        totalNum[0]--;
                        editOrderEdit.setText(totalNum[0] + "");
                    }
                    setTotalCount();
                }
            });
            editOrderAddText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (startNum[0] < totalNum[0]) {
                        startNum[0]++;
                        editOrderEdit.setText(startNum[0] + "");
                    }
                    setTotalCount();
                }
            });

            editOrderEdit.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (NumberFormatUtil.parseInt(editOrderEdit.getText().toString().trim()) > totalNum[0]) {
                        editOrderEdit.setText(totalNum[0] + "");
                        editOrderEdit.setSelection(editOrderEdit.getText().toString().length());//将光标移至文字末尾
                    }

                    setTotalCount();
//                    else if (editOrderEdit.getText().toString().trim().isEmpty()) {
//                        editOrderEdit.setText("0");
//                        editOrderEdit.setSelection(editOrderEdit.getText().toString().length());//将光标移至文字末尾
//                    }

                }
            });

            editOrderEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (!hasFocus) {
                        if (editOrderEdit.getText().toString().trim().isEmpty()) {
                            editOrderEdit.setText("0");
                            editOrderEdit.setSelection(editOrderEdit.getText().toString().length());//将光标移至文字末尾
                        }
                        setTotalCount();
                    }
                }
            });

            mEditTextList.add(editOrderEdit);
        }


    }

    private void setTotalCount() {
        int totalCount = 0;
        for (EditText editText : mEditTextList) {
            int editNum;
            if (editText.getText().toString().trim().isEmpty())
                editNum = 0;
            else
                editNum = Integer.parseInt(editText.getText().toString().trim());
            totalCount = totalCount + editNum;
        }
        editOrderTotalCountText.setText("下单总数：" + totalCount);
    }

    @Override
    protected void initTitle() {
        ImageView titleBack = (ImageView) findViewById(R.id.title_back);
        titleBack.setVisibility(View.VISIBLE);
        titleBack.setOnClickListener(this);

        TextView titleText = (TextView) findViewById(R.id.title_text);
        if (getIntent().getFlags() == Key.CLASSIFY_GOODS)
            titleText.setText(R.string.edit_order_title);
        else
            titleText.setText("编辑库存");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.goods_details_center_layout:
                BaseApplication.clearActivity();
                switchActivityAndFinish(MainActivity.class, null);
                break;
            case R.id.edit_order_submit_layout:
                boolean isHasZero = false;
                for (int i = 0; i < mGoodsSubclassList.size(); i++) {
                    if (!mGoodsSubclassList.get(i).getTotalNum().equals("0") && Integer.parseInt(mEditTextList.get(i).getText().toString()) < 1) {
                        isHasZero = true;
                        break;
                    }
                }
//                if (!isHasZero) {
                if (getIntent().getFlags() == Key.CLASSIFY_STOCK)
                    mApi = Api.EDIT_STOCK_MANAGER;
                else
                    mApi = Api.ORDER_GOODS;
                loadData(mApi, true);
//                } else {
//                    showToast("您填写的数量不能为负数或为0");
//                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void initParams(DataParams params) {
        switch (mApi) {
            case ORDER_GOODS:
            case EDIT_STOCK_MANAGER:
                String goodsSubclassIdsAndNum = "";
                if (getIntent().getFlags() == Key.CLASSIFY_STOCK) {
                    for (int i = 0; i < mGoodsSubclassList.size(); i++) {
                        if (!mEditTextList.get(i).getText().toString().isEmpty())
                            goodsSubclassIdsAndNum = goodsSubclassIdsAndNum + "," + mGoodsSubclassList.get(i).getGoodsSubclassId() + "|" + mEditTextList.get(i).getText().toString().trim();
                    }
                } else {
                    for (int i = 0; i < mGoodsSubclassList.size(); i++) {
                        if (!mGoodsSubclassList.get(i).getTotalNum().equals("0") && !mEditTextList.get(i).getText().toString().isEmpty() && Integer.parseInt(mEditTextList.get(i).getText().toString()) > 0)
                            goodsSubclassIdsAndNum = goodsSubclassIdsAndNum + "," + mGoodsSubclassList.get(i).getGoodsSubclassId() + "|" + mEditTextList.get(i).getText().toString().trim();
                    }
                }
                params.addParam("userId", PreferencesUtils.getString(Key.PER_USER_ID, ""));
                params.addParam("goodsId", getIntent().getStringExtra(Key.GOODS_ID));

                String time = System.currentTimeMillis() + "";

                if (goodsSubclassIdsAndNum.isEmpty())
                    params.addParam("goodsSubclassIdsAndNum", "");
                else
                    params.addParam("goodsSubclassIdsAndNum", goodsSubclassIdsAndNum.substring(1, goodsSubclassIdsAndNum.length()));
                params.addParam("time", time);

                List<String> dataList = new ArrayList<>();
                dataList.add(PreferencesUtils.getString(Key.PER_USER_ID, ""));
                dataList.add(getIntent().getStringExtra(Key.GOODS_ID));
                if (goodsSubclassIdsAndNum.isEmpty())
                    dataList.add("");
                else
                    dataList.add(goodsSubclassIdsAndNum.substring(1, goodsSubclassIdsAndNum.length()));
                dataList.add(time);
                try {
                    params.addParam("sign", AES.createASE(dataList));
                } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | BadPaddingException | IllegalBlockSizeException | UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }

    }

    @Override
    protected void disposeResult(Api api, String response) {
        LogUtil.d(TAG, response);
        switch (api) {
            case ORDER_GOODS:
            case EDIT_STOCK_MANAGER:
                ResultEditOrder resultEditOrder = fromJson(response, ResultEditOrder.class);
                if (!resultEditOrder.isSuccess()) {
                    showToast(resultEditOrder.getMessage());
                    return;
                }
                if (getIntent().getFlags() == Key.CLASSIFY_STOCK) {
                    showToast("修改库存成功");
                } else
                    showToast(R.string.edit_order_submit_succeed);
                finishActivityForResult();
                break;
            default:
                break;
        }
    }


}
